# made by marchen
# time at 15/3/30
# index.coffee use by views/index.ejs

lists = $ '#play-list li'
analy = $ '#analy'
allTime = $ '#allTime'
mycanvas = $ '#canvas'
canvasCtx = mycanvas[0].getContext '2d'
changeBtn = $ '.play-analy .btn'
stopAnimation1 = $ '#stop1'
WIDTH = mycanvas.width()
HEIGHT = mycanvas.height()
animation1 = null;
nowStatus = 0
x = 0
y = 0
offsetW = 1
marginW = 0

xhr = new XMLHttpRequest()
ac = new (window.AudioContext || window.webkitAudioContext)()
window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame
window.cancelRequestAnimationFrame = window.cancelRequestAnimationFrame || window.webkitcancelRequestAnimationFrame
otherSource = null
count = 0
ajaxflag = true
animageFlag = true
timeHandler = null
window.analyser = ac.createAnalyser()
window.analyser.fftSize = 2048
window.analyser.connect ac.destination

#画笔样式设置
randomColor = ->
	r = Math.floor(Math.random()*256)
	g = Math.floor(Math.random()*256)
	b = Math.floor(Math.random()*256)
	"rgb(#{r},#{g},#{b})"

array = new Uint8Array(analyser.frequencyBinCount)
canvasCtx.fillStyle = randomColor()


showEffect = (status)->
	run = ->
		if animageFlag
			requestAnimationFrame(run)
		canvasCtx.clearRect 0, 0, WIDTH, HEIGHT
		#analyser.getByteTimeDomainData(array)
		if status is 0
			analyser.getByteTimeDomainData(array)
		else if status is 1
			analyser.getByteFrequencyData(array)
		text = ''
		for value,index in array
			canvasCtx.fillRect  x, HEIGHT, -offsetW, -(value/128)*(HEIGHT/2)
			x = x + offsetW + marginW
		analy.text text
		x = 0
	requestAnimationFrame(run)

showEffect(0)

stopAnimation1.on 'click', ->
	animageFlag = if animageFlag is true then false else true;
	if animageFlag is true
	    showEffect(nowStatus)
	    $(this).text '停止动画'
	else
		$(this).text '开始动画'

load = (url)->
	clearTimeout timeHandler
	n = ++count
	otherSource?.stop 0
	if ajaxflag
		xhr.abort()
		xhr.open 'GET',url
		xhr.responseType = 'arraybuffer'
		xhr.onload = ->
			return  if n isnt count
			ac.decodeAudioData xhr.response, (buffer)->
				return  if n isnt count
				# stop other source
				source = ac.createBufferSource()
				source.buffer = buffer
				source.connect analyser
				source.start 0
				otherSource = source
			,(err)->
				console.log err
	#lock
	ajaxflag = false		
	#unlock
	timeHandler = setTimeout ->
		ajaxflag = true
	, 1000
	xhr.send()

lists.click ->
	lists.removeClass 'on'
	$(@).addClass 'on'
	fileName = $(@).attr 'title'
	load "/music/#{fileName}"


#切换效果
changeBtn.click ->
	index = $(this).index()
	if index is 0
		#时域图
		offsetW = 1
		marginW = 0
		showEffect(0)
		nowStatus = 0
	else if index is 1
		#频域图
		offsetW = 20
		marginW = 5
		showEffect(1)
		nowStatus = 1
	